<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <base href="/">
  <meta charset="utf-8">
  <link rel="stylesheet" href="order/order.css">
  <link rel="stylesheet" href="fonts/iconfont.css">
  <link rel="stylesheet" href="layui/css/layui.css">
  <title>订单提交信息</title>
</head>
<body id="top">
<div class="top-bar tonglan">
  <div class="top-nav-wrapper w">
    <div class="top-nav-left">

    </div>
    <div class="top-nav-right">

        <ul>
          <li><a href="page/index">首页</a></li><span></span>
          <li><a href="page/orderConfirm">我的订单</a></li> <span></span>
          <li><a href="page/cart">购物车</a></li> <span></span>
          <li class="lists-title"><a href="page/profile">个人中心</a></li><span></span>
          <li>
            <a href="#" id="logoutLink">退出登录</a>
          </li>
      </ul>
    </div>
  </div>
</div>
<div class="w">
  <div class="order-top">
    <a href="page/index">
    </a>
    <span>订单提交信息</span>
  </div>

<div id="products">
  <div class="order-container-wrapper" >
    <div class="order-container-title">
      <h5>商品信息</h5>
    </div>
  </div>

  </div>

  <div class="order-phone-wrapper">
    <div class="order-phone-title">
      <h5>是否上门安装？</h5>
      <span>可选择上门安装服务，需要支付一定费用</span>
    </div>
    <div class="order-installation">
      <label>是否选择上门安装服务：</label>
      <input type="radio" id="installation-yes" name="installation-choice" value="yes">
      <label for="installation-yes">是</label>
      <input type="radio" id="installation-no" name="installation-choice" value="no" checked>
      <label for="installation-no">否</label>
      <div id="installation-quantity-wrapper" style="display: none;">
        <label for="installation-quantity">请选择安装数量：</label>
        <input type="number" id="installation-quantity" value="1" min="1">
      </div>
      <span id="installation-fee" style="display: none;">安装费用：<span class="fee-amount">50</span> 元</span>
    </div>
  </div>

  <div class="order-adress-wrapper" >
    <div class="order-adress-title">
      <h5>收货地址</h5>
    </div>
    <!-- 用于显示收货地址的容器 -->
    <div name="addressbox" class="layui-row "></div>
  </div>


  <div class="order-foot">
    <div>
      <div class="div-justify">
        <p>商品件数:</p>
        <span id="total-item-count">0件</span>
      </div>
      <div class="div-justify">
        <p>商品总价：</p>
        <span id="total-product-price">0.00元</span>
      </div>
      <div class="div-justify">
        <p style="font-size: 20px; color: red; margin-top: 10px;">应付总额:</p>
        <span id="total-payable-amount" style="font-size: 20px; color: rgb(240,65,85);">0.00元</span>
      </div>
    </div>
    <div class="order-button-wrapper">
      <button id="submit-order">提交订单</button>
      <button id="back-to-cart">返回购物车</button>
    </div>
  </div>
</div>
<div class="ricker">
  <div>
    <a><i class="iconfont icon-top" id="backToTopBtn" ></i>顶部</a>
  </div>
</div>

  <iframe src="footer/footer.html" frameborder="0"></iframe>
</div>


<script src="PC/regions.js"></script>

<script src="layui/layui.all.js"></script>


<script type="text/html" id="addressitem">
  <div class='order_box_in layui-form' style="border: 1px solid orangered;margin-right: 10px; border-radius: 10px; cursor: pointer;" data-address-id="{{addressid}}">
    <div class='addressname' style="">

    </div>
    <div  style="margin-top:8px">
      地址:<span class="areatext"></span>
    </div>
    <div class='' style="margin-top:8px;">
      详细地址:<span class="addresstext"></span>
    </div>
    <div class='layui-row' style="margin-top:8px;">
      <div class=' layui-col-md6'>
        联系人:<span class="addrname"></span>
      </div>
      <div class=' layui-col-md6'>
        电话:<span class="addrphone"></span>
      </div>
    </div>
  </div>
</script>

<script id="productitem" type="text/html">
  <div class="order-container" easy="proitem">
    <input type="hidden" name="productid">
    <img easy="proimg" src="images/sp01.png" alt="">
    <div class="info-block">
      <label>商品名称</label>
      <p easy="proname"></p>
    </div>
    <div class="info-block">
      <label>商品数量</label>
      <input type="text" value="1" name="number" easy="pronumber" />
    </div>
    <div class="info-block">
      <label>商品单价</label>
      <span easy="proprice"></span>
    </div>
    <div class="info-block">
      <label>商品总价</label>
      <span easy="prototal"></span>
    </div>
    <div class="info-block">
      <label>商品类型</label>
      <h6 easy="procategory">电视</h6>
    </div>
    <button type="button" class="delete-btn">删除</button>
  </div>
</script>

<!--<script src="order/order.js"></script>-->


<script th:inline="javascript">
  const $ = layui.$;
  const layer = layui.layer;
  let selectedAddressId = null; // 用于存储选中的地址 ID



  //显示收货地址
  showAddress();
  function showAddress() {
    $.ajax({
      url: "address/getaddressbyuserid",
      success: function (result) {
        console.log("用户的信息：",result);
        let data = result.data;
        for (let i = 0; i < data.length; i++) {
          let itemtext = $("#addressitem").text();
          let $item = $(itemtext);
          $item.find(".addressname").text(data[i].addressname);
          $item.find(".areatext").text(data[i].province + "-" + data[i].city + "-" + data[i].area);
          $item.find(".addresstext").text(data[i].address);
          $item.find(".addrname").text(data[i].name);
          $item.find(".addrphone").text(data[i].phone);
          $item.attr('data-address-id', data[i].addressid); // 设置自定义属性
          if (data[i].isdefault == 1) {
            $item.addClass('selected'); // 默认地址添加选中样式
            selectedAddressId = data[i].addressid; // 默认选中的地址 ID
          }


          $("[name='addressbox']").append($item);
        }

        if (data.length < 6) {
          let itemtext = $("#addAddress").text();
          let $item = $(itemtext);
          $("[name='addressbox']").append($item);
        }

        // 监听地址项的点击事件
        $('.order_box_in').on('click', function () {
          $('.order_box_in').removeClass('selected'); // 移除所有地址项的选中样式
          $(this).addClass('selected'); // 为当前点击的地址项添加选中样式
          selectedAddressId = $(this).data('address-id'); // 更新选中的地址 ID
          console.log('选中的地址 ID:', selectedAddressId);
        });
      }
    });
  }

  //显示购买商品数据
  const  productids=/*[[${productids}]]*/;
  const counts=/*[[${counts}]]*/;
  if (!productids||!counts){
    layer.msg("系统异常，请重新选购",{icon:3})
    setTimeout(function () {
      location.href="page/index";
    },3000);
  }

  const proidArr=productids.split(",");
  const countArr=counts.split(",");
  if (proidArr.length!=countArr.length||proidArr.length==0||countArr.length==0){
    layer.msg("系统异常，请重新选购")
    setTimeout(function () {
        location.href="page/index";
    },3000);
  }

for (let i=0;i<proidArr.length;i++){
  let proid=proidArr[i];
  let count=countArr[i];
  $.ajax({
    url: "product/getproduct",
    data:{id:proid},
    async:false,
    success:function (result){
      let data=result.data;
      let item=$("#productitem").text();
      let $item=$(item);
      $item.find("[name='productid']").val(data.productid);
      $item.find("[easy='proimg']").attr("src",data.imgurl);
      $item.find("[easy='proname']").text(data.productname);
      $item.find("[easy='pronumber']").val(count);
      $item.find("[easy='proprice']").text(data.price+'.00元');
      $item.find("[easy='prototal']").text(Number(data.price)*Number(count)+'.00元');
      $item.find("[easy='procategory']").text(data.productcategory);
      $item.data('stock', data.stock);
      $("#products").append($item);
    }
  });
}
  // 监听删除按钮的点击事件
  $(document).on('click', '.delete-btn', function () {
    // 获取点击的删除按钮所在的商品信息容器
    const $productItem = $(this).closest('.order-container');
    // 移除商品信息容器
    $productItem.remove();
    //重新计算费用
    calculateFees();
  });


//是否安装监听事件
  document.addEventListener('DOMContentLoaded', function () {
    const yesRadio = document.getElementById('installation-yes');
    const noRadio = document.getElementById('installation-no');
    const quantityWrapper = document.getElementById('installation-quantity-wrapper');
    const quantityInput = document.getElementById('installation-quantity');
    const installationFee = document.getElementById('installation-fee');
    const feeAmount = document.querySelector('.fee-amount');
    const unitPrice = 50;

    // 当选择“是”时显示数量输入框和计算费用
    yesRadio.addEventListener('change', function () {
      if (this.checked) {
        quantityWrapper.style.display = 'inline';
        installationFee.style.display = 'inline';
        updateFee();
      }
    });

    // 当选择“否”时隐藏数量输入框和费用显示
    noRadio.addEventListener('change', function () {
      if (this.checked) {
        quantityWrapper.style.display = 'none';
        installationFee.style.display = 'none';
      }
    });

    // 监听数量输入框的变化，实时更新费用
    quantityInput.addEventListener('input', function () {
      updateFee();
      calculateFees();
    });

    // 计算并更新费用的函数
    function updateFee() {
      const quantity = parseInt(quantityInput.value);
      const totalFee = quantity * unitPrice;
      feeAmount.textContent = totalFee;
    }
  });
  // 计算费用的函数
  function calculateFees() {
    let totalItemCount = 0;
    let totalProductPrice = 0;
    const $productItems = $('.order-container');
    $productItems.each(function () {
      const count = parseInt($(this).find('[easy="pronumber"]').val());
      const price = parseFloat($(this).find('[easy="proprice"]').text().replace('元', ''));
      totalItemCount += count;
      totalProductPrice += count * price;
    });

    const installationFee = document.getElementById('installation-fee');
    let totalInstallationFee = 0;
    if (installationFee.style.display === 'inline') {
      const quantityInput = document.getElementById('installation-quantity');
      const quantity = parseInt(quantityInput.value);
      const unitPrice = 50;
      totalInstallationFee = quantity * unitPrice;
    }

    const totalPayableAmount = totalProductPrice + totalInstallationFee;

    $('#total-item-count').text(totalItemCount + '件');
    $('#total-product-price').text(totalProductPrice.toFixed(2) + '元');
    $('#total-payable-amount').text(totalPayableAmount.toFixed(2) + '元');
  }

  // 初始计算费用
  calculateFees();

  // 返回购物车按钮点击事件
  $('#back-to-cart').on('click', function () {
    window.location.href = 'page/cart';
  });

  const backToTopBtn = document.getElementById('backToTopBtn');
  backToTopBtn.addEventListener('click', function () {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  });

  // 提交订单按钮点击事件
  $('#submit-order').on('click', function () {
    // 检查库存
    let hasInsufficientStock = false;
    $('.order-container').each(function () {
      const count = parseInt($(this).find('[easy="pronumber"]').val());
      const stock = parseInt($(this).data('stock'));
      if (count > stock) {
        hasInsufficientStock = true;
        const productName = $(this).find('[easy="proname"]').text();
        layer.msg(`商品 ${productName} 库存不足，当前库存：${stock}`, { icon: 2 });
      }
    });

    if (hasInsufficientStock) {
      return; // 阻止提交订单
    }

    // 收集订单数据
    const productIds = [];
    const productCounts = [];
    const productPrices = []; // 新增：收集商品单价
    $('.order-container').each(function () {
      const productId = $(this).find('[name="productid"]').val();
      const count = $(this).find('[easy="pronumber"]').val();
      const price = parseFloat($(this).find('[easy="proprice"]').text().replace('元', '')); // 新增：获取商品单价
      productIds.push(productId);
      productCounts.push(count);
      productPrices.push(price); // 新增：添加商品单价到数组
    });

    const installationChoice = $('input[name="installation-choice"]:checked').val();
    const installationQuantity = $('#installation-quantity').val();
    const totalPayableAmount = $('#total-payable-amount').text().replace('元', '');
    const isUpset = installationChoice === 'yes' ? 1 : 0; // 根据上门安装选择设置 isupset 的值

    // 获取选中地址的详细信息
    const selectedAddress = $('.order_box_in.selected');
    const address = selectedAddress.find('.areatext').text() + ' ' + selectedAddress.find('.addresstext').text();
    const name = selectedAddress.find('.addrname').text();
    const tel = selectedAddress.find('.addrphone').text();

    const orderData = {
      productIds: productIds.join(','),
      productCounts: productCounts.join(','),
      productPrices: productPrices.join(','), // 新增：添加商品单价到订单数据
      installationChoice: installationChoice,
      installationQuantity: installationQuantity,
      totalPayableAmount: totalPayableAmount,
      addressId: selectedAddressId,
      isupset: isUpset, // 添加 isupset 到订单数据中
      address: address,
      name: name,
      tel: tel
    };

    console.log('提交的订单数据:', orderData);


    // 发送 AJAX 请求
    $.ajax({
      url: 'order/submit',
      type: 'POST',
      contentType: 'application/json',
      data: JSON.stringify(orderData),
      success: function (result) {
        if (result.code === 200) {
          layer.msg('订单提交成功', { icon: 1 });
          setTimeout(function () {
            window.location.href = 'page/orderConfirm';
          }, 2000);
        } else {
          layer.msg('订单提交失败', { icon: 2 });
        }
      },
      error: function (error) {
        layer.msg('订单提交失败，重试', { icon: 2 });
      }
    });
  });
  // 退出登录逻辑
  const logoutLink = document.getElementById('logoutLink');
  logoutLink.addEventListener('click', function (e) {
    e.preventDefault(); // 阻止默认的链接跳转行为
    // 弹出确认提示框
    if (confirm('确定要退出登录吗？')) {
      $.ajax({
        url: 'logout', // 后端退出登录的接口地址
        method: 'GET',
        success: function (response) {
          if (response.code === 200) {
            // 退出登录成功，给出提示并跳转到登录页面
            alert(response.msg);
            window.location.href = 'page/login';
          } else {
            // 退出登录失败，给出提示
            alert(response.msg);
          }
        },
        error: function (error) {
          console.error('退出登录失败:', error);
          alert('退出登录时发生错误，请稍后再试。');
        }
      });
    }
  });
</script>
<script src="PC/regions_picker.js"></script>
</body>
</html>